<?php
/**
 * Created by PhpStorm.
 * User: baidu
 * Date: 17/7/28
 * Time: 上午12:27
 */
namespace app\common\lib\aes;
use think\Cache;

class IAuth {

    /**
     * 生成每次请求的sign
     * @param array $data
     * @author 王柯 <wangke.email@foxmail.com>
     * @return HexString|string
     */
    public static function setSign($data = []) {
        // 1 按字段排序
        ksort($data);
        // 2拼接字符串数据  &
        $string = http_build_query($data);
        // 3通过aes来加密
        $string = (new Aes())->encrypt($string);//HxSpztQ2SkXnyHM1og6o5QUCL4EomQEMaWgQsFY1y1VwU9B2z0U8WSNb9Ghnbk3URESbG6UOzM+rHLqpbO5HBYExhHxM4U9aMDzkroR1ShM=
        //dump($string);exit;
        return $string;
    }

    /**
     * 检查sign是否正常
     * @param array $data
     * @author 王柯 <wangke.email@foxmail.com>
     * @return bool
     */
    public static function checkSignPass($data) {
        $str = (new Aes())->decrypt($data['sign']);
        if(empty($str)) {
            return false;
        }
        //did=xx&app_type=android&
        parse_str($str, $arr);
        //dump($arr);exit;
        if(!is_array($arr) || empty($arr['did'])
            || $arr['did'] != $data['did']
        ) {
            return false;
        }

        if(!config('app_debug')) {
            if ((time() - ceil($arr['time'] / 1000)) > config('app.app_sign_time')) {
                return false;
            }
            // 唯一性判定
            if (Cache::get($data['sign'])) {
                return false;
            }
        }
        return true;
    }

    /**
     * 设置登录的token  - 唯一性的
     * @param string $phone
     * @author 王柯 <wangke.email@foxmail.com>
     * @return string
     */
    public static function setAppLoginToken($phone = '') {
        $str = md5(uniqid(md5(microtime(true)), true));
        $str = sha1($str.$phone);
        return $str;
    }

}